package thesis.filesharing.bo.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import thesis.filesharing.bo.ClassBO;
import thesis.filesharing.common.exception.functional.InvalidArgumentException;
import thesis.filesharing.common.exception.functional.ObjectNotFoundException;
import thesis.filesharing.common.valueobjects.SearchClassValueObject;
import thesis.filesharing.dao.ClassDAO;
import thesis.filesharing.model.Clazz;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@Service
public class ClassBOImpl implements ClassBO {
	
	@Autowired
	private ClassDAO classDAO;
	
	@Override
	public Clazz findClassByIdAndSemester(String classId, Integer semester) {
		return classDAO.findClassByIdAndSemester(classId, semester);
	}

	@Override
	public Clazz findClassByKey(String key) {
		Key classKey = KeyFactory.stringToKey(key);
		return classDAO.findClassByKey(classKey);
	}

	@Override
	public List<Clazz> listClasses(int page, int pageSize) {
		if (page < 1 || pageSize < 1) {
			throw new InvalidArgumentException();
		}
		return classDAO.listClasses(page, pageSize);
	}

	@Override
	public Clazz saveClass(Clazz clazz, Key subjectKey) {
		return classDAO.saveClass(clazz, subjectKey);
	}

	@Override
	public Clazz updateClass(Clazz clazz, String subjectId) {
		return classDAO.updateClass(clazz, subjectId);
	}

	@Override
	public void deleteClass(String key) {
		Key classKey = KeyFactory.stringToKey(key);
		Clazz c = classDAO.findClassByKey(classKey);
		if (c == null) {
			throw new ObjectNotFoundException(new Exception("Class has this key could not be found"), Clazz.class);
		}
		classDAO.deleteClass(classKey);
	}

	@Override
	public int countClasses() {
		return classDAO.countClasses();
	}

	@Override
	public boolean checkClassIdExistedInSemester(String classId, Integer semester) {
		return classDAO.checkClassIdExistedInSemester(classId, semester);
	}

	@Override
	public List<Clazz> searchClasses(SearchClassValueObject searchObj,
			int page, int pageSize) {
		if (page < 1 || pageSize < 1) {
			throw new InvalidArgumentException();
		}
		return classDAO.searchClasses(searchObj, page, pageSize);
	}

	@Override
	public int countFoundClasses(SearchClassValueObject searchObj) {
		return classDAO.countFoundClasses(searchObj);
	}

	@Override
	public void addStudentToClass(String studentId, String classId) {
		classDAO.addStudentToClass(studentId, classId);
	}

	@Override
	public void deleteStudentFromClass(String studentKey, String classKey) {
		classDAO.deleteStudentFromClass(KeyFactory.stringToKey(studentKey), KeyFactory.stringToKey(classKey));
	}

	@Override
	public List<Clazz> searchClasses(SearchClassValueObject searchObj) {
		return classDAO.searchClasses(searchObj);
	}
}
